<template>
    <div class="tou">
        <!-- 条件查询 -->
        <el-form>
            <el-row :gutter="20">
                <el-col :span="6" :offset="0">
                    <el-form-item label="单据编号：">
                        <el-input v-model="purchase.number" placeholder="请输入单据编号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6" :offset="0">
                    <el-form-item label="商品信息：">
                        <el-input v-model="purchase.commodities" placeholder="请输入条码、名称、规格、型号、颜色、扩展信息"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6" :offset="0">
                    <el-form-item label="单据日期：">
                        <div class="demo-date-picker">
                            <div class="block">
                                <el-date-picker v-model="billDate" 
                                style="width: 94%;" 
                                format="YYYY-MM-DD HH:mm:ss"
                                type="datetimerange" 
                                range-separator="~" 
                                value-format="YYYY-MM-DD HH:mm:ss"
                                start-placeholder="开始时间" 
                                end-placeholder="结束时间" 
                                prefix-icon="display" />
                            </div>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="6" :offset="0">
                    <el-form-item>
                        <el-button type="primary" @click="init">查询</el-button>
                        <el-button @click="reset">重置</el-button>
                        <a style="margin-left: 8px;" @click="ss">
                            {{linkText}}
                            <i class="anticon anticon-down" v-show="!isDivVisible">
                                <svg viewBox="64 64 896 896" data-icon="down" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class=""><path d="M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z"></path></svg>
                            </i>
                            <i class="anticon" v-show="isDivVisible">
                                <svg viewBox="64 64 896 896" data-icon="up" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class=""><path d="M890.5 755.3L537.9 269.2c-12.8-17.6-39-17.6-51.7 0L133.5 755.3A8 8 0 0 0 140 768h75c5.1 0 9.9-2.5 12.9-6.6L512 369.8l284.1 391.6c3 4.1 7.8 6.6 12.9 6.6h75c6.5 0 10.3-7.4 6.5-12.7z"></path></svg>
                            </i>
                        </a>
                    </el-form-item>
                </el-col>
            </el-row>
            <div v-show="isDivVisible">
                <el-row :gutter="20">
                    <el-col :span="6" :offset="0">
                        <el-form-item label="供应商：">
                            <el-select v-model="purchase.supId" placeholder="请选择供应商">
                                <el-option v-for="item in suppliers" :key="item.supId" :label="item.supName"
                                    :value="item.supId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="0">
                        <el-form-item label="仓库名称：">
                            <el-select v-model="purchase.depId" placeholder="请选择仓库">
                                <el-option v-for="depot in depots" :key="depot.id" :label="depot.name"
                                    :value="depot.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="0">
                        <el-form-item label="操作员：">
                            <el-select v-model="purchase.userId" placeholder="请选择操作员">
                                <el-option v-for="item in users" :key="item.value" :label="item.username"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="0">
                        <el-form-item label="关联订单：">
                            <el-input v-model="purchase.linkNumber" placeholder="请输入关联订单"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="0">
                        <el-form-item label="结算账户：">
                            <el-select v-model="purchase.accId" placeholder="请选择结算账户">
                                <el-option v-for="item in accounts" :key="item.accId" :label="item.name"
                                    :value="item.accId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="0">
                        <el-form-item label="有无欠款：">
                            <el-select v-model="purchase.debt" placeholder="请选择有无欠款">
                                <el-option v-for="item in debts" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="0">
                        <el-form-item label="单据状态：">
                            <el-select v-model="purchase.status" placeholder="请选择单据状态">
                                <el-option v-for="item in docStatus" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="0">
                        <el-form-item label="单据备注：">
                            <el-input v-model="purchase.remark" placeholder="请输入单据备注"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
        </el-form>
        <!-- 新增 -->
         <el-button class="ant-btn ant-btn-primary" 
         v-perm:purchase:in:insert="insert">
            <i class="anticon">
                <svg viewBox="64 64 896 896" data-icon="plus" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class=""><path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"></path><path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path></svg>
            </i>
            <span style="margin-left: 8px;">
                新增
            </span>
        </el-button>
        <!-- 批量操作 -->
        <el-dropdown>
            <el-button class="ant-btn" style="margin-left: 8px;">
                批量操作<el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
                <el-dropdown-menu>
                    <template v-for="item in strBtn">
                        <template v-if="item === '编辑'">
                            <el-dropdown-item @click="removes">
                                <el-icon><Delete /></el-icon>
                                <span>删除</span>
                            </el-dropdown-item>
                        </template>
                        <template v-else-if="item === '审核'">
                            <el-dropdown-item @click="modifyTheState(1)">
                            <el-icon>
                                <Select />
                            </el-icon>
                            <span>{{ item }}</span>
                            </el-dropdown-item>
                        </template>
                        <template v-else>
                            <el-dropdown-item @click="modifyTheState(0)">
                            <el-icon>
                                <CircleClose />
                            </el-icon>
                            <span>{{ item }}</span>
                            </el-dropdown-item>
                        </template>
                    </template>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
        
        <!-- 分页内容显示 -->
        <div style="margin-top: 6px;">
            <el-table :data="page.records" border stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="操作" min-width="120" align="center" width="220">
                    <template #default="scope">
                        <el-button link type="primary" :row="scope.row" v-perm:purchase:in:check="checkPurchase">
                        查看
                        </el-button>
                        <el-button link type="primary" :row="scope.row" v-perm:purchase:in:update="update">
                        编辑
                        </el-button>
                        <el-button link type="primary" :row="scope.row" v-perm:purchase:in:copy="copy">
                        复制
                        </el-button>
                        <el-button link type="primary" :row="scope.row" v-perm:purchase:in:remove="remove">删除</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="供应商" prop="supName" width="120"/> 
                <el-table-column label="单据编号" prop="number"/> 
                <el-table-column label="商品信息" prop="materialName" /> 
                <el-table-column label="单据日期" prop="operTime" width="180"/> 
                <el-table-column label="操作员" prop="username" width="80"/> 
                <el-table-column label="数量" prop="totalQuantity" width="80"/> 
                <el-table-column label="金额合计" prop="totalPrice" width="100"/> 
                <el-table-column label="含税合计" prop="discountLastMoney" width="100"/>
                <el-table-column label="待付金额" prop="waitMoney" width="100"/>
                <el-table-column label="付款" prop="changeAmount" width="80"/>
                <el-table-column label="欠款" prop="debt" width="80"/>
                <el-table-column label="状态" prop="status" width="100" align="center">
                    <template #default="records">
                        <el-tag v-if="records.row.status == 0" type="danger" effect="light">
                        未审核
                        </el-tag>
                        <el-tag v-else-if="records.row.status == 1" type="success" effect="light">
                        已审核
                        </el-tag>
                        <el-tag v-else-if="records.row.status == 2" type="warning" effect="light">
                        完成退货
                        </el-tag>
                        <el-tag v-else-if="records.row.status == 3" type="primary" effect="light">
                        部分退货
                        </el-tag>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页组件 -->
        <el-pagination 
            v-model:page-size="page.size" 
            v-model:current-Page="page.current"
            @current-change="init"
            @size-change="init"
            :page-sizes="[5, 10, 15]" 
            layout="total, prev, pager, next, sizes, jumper" 
            :total="page.total" 
            style="float: right;margin-top: 10px;">
        </el-pagination>
        <!-- 弹框 -->
        <el-dialog
            :title="title"
            v-model="visible"
            width="70%" 
            top="20vh"
            :destroy-on-close="true">
            <router-view :data="data" @close="close"></router-view>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, defineProps } from 'vue';
import router from '@/router';
import request from '@/api/request'
import { ElMessage } from 'element-plus';

let props = defineProps(['strBtn'])
console.log("strBtn",props.strBtn);
let page = ref([])
let visible = ref(false)
let title = ref("")
let data = ref({})
let linkText = ref('展开')
let isDivVisible = ref(false)
//时间
let billDate = ref([])
//查询参数
let purchase = ref({})
//供应商
let suppliers = ref([])
//结算用户
let accounts = ref([]);
//操作员
let users = ref([])
//仓库
let depots = ref([]);
//单据状态
let docStatus = [
  {value: 0, label: '未审核',},
  {value: 1, label: '已审核',}
]
//有无欠款
let debts = [
  {value: '有欠款', label: '有欠款',},
  {value: '无欠款', label: '无欠款',}
]
//初始化
let init = () =>{
    // 先获取表单中选择的欠款状态
    let selectedDebtStatus = purchase.value.debt;
    if(billDate.value){
        purchase.value.startTime=billDate.value[0];
        purchase.value.endTime=billDate.value[1];
    }
    purchase.value.current=page.value.current;
    purchase.value.size=page.value.size;
    purchase.value.subType="采购";
    request({
        url: '/purchase/order/PurchaseFindByPage',
        method: "post",
        data: purchase.value
    }).then(res => {
        let records = res.data.records.map(record => ({
            ...record,//服务器获取的记录数组，map遍历数组，将其中的字段取出来，组成新的对象，然后返回给records数组
            debtStatus: record.debt > 0 ? '有欠款' : '无欠款'//如果大于0，则有欠款，否则无欠款
        })).filter(record => {
            //filter方法过滤数组，返回符合条件的数组
            if (selectedDebtStatus == null) return true; // 如果没有选择，则显示所有
            return record.debtStatus == selectedDebtStatus;//如果选择的欠款状态和记录的欠款状态一致，则显示，否则不显示
        });

        page.value.records = records;//把值重新赋值给page显示
        page.value.total = res.data.total;//总行数也赋值给page显示  

        // setTimeout(() => {
        //     loading.value = false;
        // }, 100);//挂载table查询每次当条件或者页码变动时都会调用loadMenus方法
    })
}
init();

//重置
let reset = () =>{
    purchase.value = ({})
    billDate.value = ([])
    init();
}

//查询供应商
let findsuppliers = () =>{
    request({
        url:'/basic/vendor/findSuppliers',
        method: 'get'
    }).then(resp =>{
        suppliers.value = resp.data
    })
}
findsuppliers();

//查询结算用户
let findaccounts = () => {
  request({
    url: "/basic/account/list",
    method: "get",
  }).then((resp) => {
    accounts.value = resp.data;
  });
};
findaccounts();

//查询仓库
let loadDepot = () => {
    request({
        url: '/depot/list',
        method: 'get'
    }).then(res => {
        depots.value = res.data;
    }).catch(err => {
        console.error(err);
    });
};
loadDepot();

//查询操作员
let findusers = () =>{
    request({
        url:'/user/user',
        method: 'get'
    }).then(resp =>{
        users.value = resp.data
    })
}
findusers();

let ss =()=>{
    isDivVisible.value = !isDivVisible.value;
    linkText.value = isDivVisible.value ? '收起' : '展开'
}

//跳转新增页面
let insert = (menu) => {
  title.value = menu.cname;
  visible.value = true;
  router.push(menu.path);
};

//跳转查看页面
let checkPurchase =(menu, row)=>{
    title.value = menu.cname;
    visible.value = true;
    data.value = row;
    router.push(menu.path);
}

//跳转复制页面
let copy =(menu, row)=>{
    title.value = menu.cname;
    visible.value = true;
    data.value = row;
    router.push(menu.path);
}

//跳转修改页面
let update =(menu, row)=>{
    if (row.status != 0) {
        ElMessage.warning('抱歉，只有未审核的单据才能编辑！');
        return;
    }
    title.value = menu.cname;
    visible.value = true;
    data.value = row;
    router.push(menu.path);
}

//多选值
let multipleSelection = ref([])
let ids = ref([]);

//获取多选的值转入multipleSelection中
let handleSelectionChange =(val)=>{
    multipleSelection.value = val;
    ids.value = val.map(item => item.id);
}

//删除
let remove = (menu, row) => {
    console.log(row.status)
    if (row.status != 0) {
        ElMessage.warning('抱歉，只有未审核的单据才能删除！');
        return;
    }
    request.delete("/purchase/order/remove/" + row.id)
    .then(resp => {
        ElMessage.success(resp.data);
        init();
    });
};

//批量删除
let removes = () => {
    if (ids.value.length === 0) {
        ElMessage.warning('请先选择至少一项记录');
        return;
    }

    let allApproved = true; // 假设所有选中的项都是未审核的
    multipleSelection.value.forEach(item => {
        if (item.status != 0) {
            console.log(item.status);
            ElMessage.warning('抱歉，只有未审核的单据才能删除！');
            allApproved = false; // 发现有已审核的项，设置标志为false
        }
    });
 
    if (allApproved) {
        request.delete("/sale/delete", {
            data: ids.value
        }).then(resp => {
            ElMessage.success(resp.data);
            init();
        }).catch(error => {
            ElMessage.error('删除失败，请重试！');
            console.error(error);
        });
    }
};


//审核
let modifyTheState = (num) =>{
    if (ids.value.length === 0) {
        ElMessage.warning('请先选择至少一项记录');
        return;
    }

    let allApproved = true; 
    if (num == 1){
        multipleSelection.value.forEach(item => {
            if (item.status != 0) {
                ElMessage.warning('抱歉，只有未审核的单据才能审核！');
                allApproved = false; 
                return;
            }
        });
    } else {
        multipleSelection.value.forEach(item => {
            if (item.status != 1) {
                ElMessage.warning('抱歉，只有已审核的单据才能反审核！');
                allApproved = false;
                return;
            }
        });
    }
    
    if (allApproved) {
        request.put("/purchase/order/modifyTheState", {
            ids : ids.value,
            status : num
        }).then(resp => {
            ElMessage.success(resp.data);
            init();
        }).catch(error => {
            ElMessage.error('操作失败，请重试！');
            console.error(error);
        });
    }
}

let close = ()=>{
    init();
    visible.value = false;
}
</script>

<style scoped>
.tou {
    float: left;
    position: relative;
    width: 100%;
}

.el-form-item {
    margin-right: 12px;
    vertical-align: middle;
}

a:active, a:hover {
    text-decoration: none;
    outline: 0;
}

a:hover {
    color: #40a9ff;
}

a {
    color: #1890ff;
    text-decoration: none;
    background-color: transparent;
    outline: none;
    cursor: pointer;
    transition: color .3s;
    -webkit-text-decoration-skip: objects;
}

.anticon {
    display: inline-block;
    color: inherit;
    font-style: normal;
    line-height: 0;
    text-align: center;
    text-transform: none;
    vertical-align: -.125em;
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.anticon svg {
    display: inline-block;
}

.ant-btn {
    line-height: 1.499;
    position: relative;
    display: inline-block;
    font-weight: 400;
    white-space: nowrap;
    text-align: center;
    background-image: none;
    border: 1px solid transparent;
    box-shadow: 0 2px 0 rgba(0, 0, 0, .015);
    cursor: pointer;
    transition: all .3s cubic-bezier(.645,.045,.355,1);
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    height: 32px;
    padding: 0 15px;
    font-size: 14px;
    border-radius: 4px;
    color: rgba(0, 0, 0, .65);
    background-color: #fff;
    border-color: #d9d9d9;
}

.ant-btn:hover {
    color: #40a9ff;
    background-color: #fff;
    border-color: #40a9ff;
}

.ant-btn-primary {
    color: #fff;
    background-color: #1890ff;
    border-color: #1890ff;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, .12);
    box-shadow: 0 2px 0 rgba(0, 0, 0, .045);
}

.ant-btn-primary:focus, .ant-btn-primary:hover {
    color: #fff;
    background-color: #40a9ff;
    border-color: #40a9ff;
}
</style>
